from flask import render_template, session, request, jsonify

from models import db
from models.index import User, Article, Classify
from . import admin_blu


@admin_blu.route("/admin")
def admin():
    user_id = session.get("user_id")
    user = db.session.query(User).filter(User.id == user_id).first()
    if user.admin == True:
        article = db.session.query(Article).all()
        return render_template('admin/admin.html', user=user, article=article)
    else:
        return render_template('index/user.html', user=user)


@admin_blu.route("/admin/classify")
def classify():
    user_id = session.get("user_id")
    user = db.session.query(User).filter(User.id == user_id).first()
    classify = db.session.query(Classify).filter(Classify.status == 1).all()
    return render_template('admin/classify.html', user=user, classify=classify)


@admin_blu.route("/admin/user")
def user():
    user_id = session.get("user_id")
    user = db.session.query(User).filter(User.id == user_id).first()
    other = db.session.query(User).all()
    return render_template('admin/user.html', user=user, other=other)


@admin_blu.route("/admin/change_admin", methods=['POST'])
def change_admin():
    user_id = request.json.get('user_id')
    user = db.session.query(User).filter(User.id == user_id).first()
    if user.admin == True:
        user.admin = False
    else:
        user.admin = True
    try:
        db.session.commit()
        ret = {"err": 0, "errmsg": "修改权限成功"}
    except Exception:
        ret = {"err": 101, "errmsg": "修改权限失败，请稍后重试"}
    return jsonify(ret)
